<?php

namespace app\common\controller;

use think\Db;

class Elasticsearch
{

    protected $client; //客户端实例

    protected $params_index; //索引名称

    protected $params_mappings; //type

    private $searchParamsd; //查询条件等

    private $page;    //第几页  //分页参数

    private $limit;   //几条    //分页参数


    /**
     * @title elasticsearch
     * @description elasticsearch
     * @author 李正
     */
    function __construct()
    {
        //索引名

        $this->params_index = Config()['app']['params_index'];
        //type
        $this->params_mappings = Config()['app']['params_mappings'];
        //host数组可配置多个节点
        $params = Config()['app']['elasticsearch_host'];
        $this->client = \Elasticsearch\ClientBuilder::create()->setHosts($params)->build();  //实例化客户端

        /**查询判断是否有索引 是否需要创建索引**/
        $res = $this->client->indices()->getSettings(['index' => $this->params_index]);
        if (!empty($res['error'])) {
            //设置索引字段
            $properties = [
                'name' => [
                    'type' => 'text',
                    'analyzer' => 'standard'
                ],
                'content' => [
                    'type' => 'text',
                    'analyzer' => 'standard'
                ],
                'addtime' => [
                    'type' => 'text',
                    'analyzer' => 'standard'
                ]
            ]; //索引字段

            /**配置索引所需参数 生成索引**/
            $properties['tag'] = [
                'properties' => ['tagName' => ['type' => 'text'], 'tagWeight' => ['type' => 'integer',]]
            ];
            $params = [
                'index' => $this->params_index,  //索引名（相当于mysql的数据库）
                'body' => [
                    'settings' => [
                        'number_of_shards' => Config()['app']['number_of_shards'],
                        'number_of_replicas' => Config()['app']['number_of_replicas']
                    ],
                    'mappings' => [
                        $this->params_mappings => [ //类型名（相当于mysql的表）
                            '_source' => [
                                'enabled' => Config()['app']['enabled']
                            ],
                            'properties' => $properties //文档类型设置（相当于mysql的数据类型）
                        ]
                    ]
                ]
            ];
            $this->client->indices()->create($params);
        }
    }

    /**
     * @title addSingleElastics单条数据插入
     * @description addSingleElastics单条数据插入
     * @author 李正
     * @param name:data require:1 default: desc:日志数据
     * @return data 记录id
     * @method *
     */
    public function addSingleElastics($data)
    {

        if(is_array($data['content'])){
            $data['content'] = var_export($data['content'], True);
        }
        $data['addtime'] = time();
        $params = [
            'index' => $this->params_index,
            'type' => $this->params_mappings,
            'body' => $data
        ];
        $response = $this->client->index($params);
        return $response['_id'];
    }

    protected function clients()
    {
        return $this->client;
    }

    //获取 分页参数
    //分页调用
    private function infrom()
    {
        $data = input();
        $this->page = ($data['page'] == 1) ? 0 : $data['page'];
        $this->limit = $data['limit'];
    }

    //查询条件  == mysql的where 但是只能查询一个条件
    public function WhereElastice($data)
    {
        $this->searchParamsd['body']['query']['match'] = $data;
    }

    /**
     * @title elasticsearch -- 查询
     * @description elasticsearch -- 查询
     * @author 李正
     * @param name:page require:true default: desc:需要分页传true  默认查询所有
     * @return
     * @method *
     */
    public function getElastice($page = false)
    {

        //指定索引
        $dats = [];
        $this->searchParamsd['index'] = $this->params_index;
        $this->searchParamsd['type'] = $this->params_mappings;

        //判断是否需要分页
        $this->infrom();
        if ($page) {
            $this->searchParamsd['body']['from'] = $this->page;
            $this->searchParamsd['body']['size'] = $this->limit;
        }
        $retDoc = $this->client->search($this->searchParamsd);
        //分页信息、整理数据
        $dats['total'] = $retDoc['hits']['total'];
        $dats['current_page'] = ($this->page == '0') ? 1 : $this->page;
        $dats['per_page'] = $this->limit;
        $dats['last_page'] = $retDoc['hits']['max_score'];

        if ($retDoc['hits']['total'] == 0) {
            return $dats['data'] = [];
        }
        foreach ($retDoc['hits']['hits'] as $k => $v) {
            $dats['data'][$k] = $v['_source'];
            $dats['data'][$k]['id'] = $v['_id'];

        }
        return $dats;
    }

    /**
     * @title elasticsearch -- 删除索引
     * @description elasticsearch -- 删除索引
     * @author 李正
     * @param name:id require:true default: desc:需要删除的索引名
     * @return
     * @method *
     */
    public function delindex($name)
    {
        $params = [
            'index' => $name,  //索引名（相当于mysql的数据库）
        ];
        $res = $this->client->indices()->delete($params);
        if (empty($res['error'])) {
            return true;
        }
        return false;
    }

    /**
     * @title elasticsearch -- 删除数据
     * @description elasticsearch -- 删除数据
     * @author 李正
     * @param name:id require:true default: desc:需要删除的数据id
     * @return
     * @method *
     */
    public function delElastice($id)
    {
        $param = [
            'index' => $this->params_index,
            'type' => $this->params_mappings,
            'id' => $id
        ];
        $ret = $this->client->delete($param);
        if ($ret['result'] == "not_found") {
            return false;
        }
        return true;
    }
}
